package cn.z2huo.knowledge.concurrency.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * <p>
 *
 * @author z2huo
 */
class SimpleMockLock implements Lock {

    private final Sync sync = new Sync();

    @Override
    public void lock() {
        // 委托给自定义同步器的 acquire 方法
        sync.acquire(1);
    }

    @Override
    public void unlock() {
        // 委托给自定义同步器的 release 方法
        sync.release(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public Condition newCondition() {
        return null;
    }

    /**
     * <p>自定义同步器
     * state = 1 表示锁没有被占用
     * state = 0 表示锁已经被占用
     */
    private static class Sync extends AbstractQueuedSynchronizer {

        @Override
        protected boolean tryAcquire(int arg) {
            // CAS 更新状态值为 1
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            // 释放锁时，如果当前线程不是占用锁的线程，否则抛出异常
            if (Thread.currentThread() != getExclusiveOwnerThread()) {
                throw new IllegalMonitorStateException();
            }
            // 释放锁时，状态值必须为 1，否则抛出异常
            if (getState() == 0) {
                throw new IllegalMonitorStateException();
            }
            // 释放锁时，将独占锁的拥有线程设置为 null
            setExclusiveOwnerThread(null);
            // 设置状态
            setState(0);
            return true;
        }

    }



}
